<template>
  <div class="workflow-drawer-node">
    <el-form
      :model="state.node"
      :rules="nodeRules"
      ref="nodeFormRef"
      size="default"
      label-width="90px"
      class="pa8"
    >
      <el-form-item label="数据id" prop="id" required>
        <el-input v-model="state.node.id" placeholder="请输入数据id" clearable></el-input>
      </el-form-item>
      <el-form-item label="节点id" prop="nodeId">
        <el-input
          v-model="state.node.nodeId"
          placeholder="请输入节点id"
          clearable
          disabled
        ></el-input>
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-input v-model="state.node.type" placeholder="请输入类型" clearable disabled></el-input>
      </el-form-item>
      <el-form-item label="left坐标" prop="left">
        <el-input
          v-model="state.node.left"
          placeholder="请输入left坐标"
          clearable
          disabled
        ></el-input>
      </el-form-item>
      <el-form-item label="top坐标" prop="top">
        <el-input
          v-model="state.node.top"
          placeholder="请输入top坐标"
          clearable
          disabled
        ></el-input>
      </el-form-item>
      <el-form-item label="icon图标" prop="icon">
        <IconSelector :icons="['ali']" placeholder="请输入icon图标" v-model="state.node.icon" />
      </el-form-item>
      <el-form-item label="名称" prop="label">
        <el-input v-model="state.node.label" placeholder="请输入名称" clearable></el-input>
      </el-form-item>
      <el-form-item
        :label="item.label"
        :prop="item.prop"
        v-for="(item, key) in state.node.form || []"
        :key="key"
        :rules="[{ required: item.required, message: `${item.label}不能为空`, trigger: 'blur' }]"
      >
        <el-input
          v-if="['el-input'].includes(item.type)"
          v-model="state.node[item.prop]"
          :placeholder="item.placeholder"
          :clearable="item.clearable || false"
          :disabled="item.disabled"
        ></el-input>
        <div v-else-if="['el-select'].includes(item.type)" class="flex align-center flex-grow">
          <SvgIcon
            name="ele-Avatar"
            class="mr5"
            :class="state.node[item.prop] ? 'color-primary' : 'color-danger'"
            v-if="state.node.approvalUserType === 1 && ['roleId'].includes(item.prop)"
          />
          <SvgIcon
            name="ele-InfoFilled"
            class="mr5"
            :class="state.node[item.prop] ? 'color-primary' : 'color-info'"
            v-if="
              state.node.approvalUserType === 2 && ['roleType', 'roleRelType'].includes(item.prop)
            "
          />
          <el-select
            v-model="state.node[item.prop]"
            :placeholder="item.placeholder"
            :multiple="item.prop === 'formEditItemList'"
            :clearable="item.clearable"
            :disabled="item.disabled"
            :filterable="item.filterable"
            class="flex-grow"
          >
            <el-option
              v-for="option in getOptions(item)"
              :key="option.field"
              :label="option.title"
              :value="option.field"
            ></el-option>
          </el-select>
        </div>
        <el-switch
          v-if="['el-switch'].includes(item.type)"
          v-model="state.node[item.prop]"
          :disabled="item.disabled"
        ></el-switch>
      </el-form-item>
      <el-form-item v-if="!hideTool">
        <el-button class="mb15" @click="onNodeRefresh">
          <SvgIcon name="ele-RefreshRight" />
          重置
        </el-button>
        <el-button type="primary" class="mb15" @click="onNodeSubmit">
          <SvgIcon name="ele-Check" />
          保存
        </el-button>
      </el-form-item>
    </el-form>
    <!--    <el-tabs type="border-card" v-model="state.tabsActive">-->
    <!--      <el-tab-pane label="节点编辑" name="1">-->
    <!--        <el-scrollbar>-->
    <!--          -->
    <!--        </el-scrollbar>-->
    <!--      </el-tab-pane>-->
    <!--      <el-tab-pane label="扩展表单" name="2">-->
    <!--        <el-scrollbar>-->
    <!--          <el-form-->
    <!--            :model="state.node"-->
    <!--            ref="extendFormRef"-->
    <!--            size="default"-->
    <!--            label-width="80"-->
    <!--            class="pt15 pr15 pb15 pl15"-->
    <!--          >-->
    <!--            <el-form-item>-->
    <!--              <el-button class="mb15" @click="onExtendRefresh">-->
    <!--                <SvgIcon name="ele-RefreshRight"/>-->
    <!--                重置-->
    <!--              </el-button>-->
    <!--              <el-button-->
    <!--                type="primary"-->
    <!--                class="mb15"-->
    <!--                @click="onNodeSubmit"-->
    <!--                :loading="state.loading.extend"-->
    <!--              >-->
    <!--                <SvgIcon name="ele-Check"/>-->
    <!--                保存-->
    <!--              </el-button>-->
    <!--            </el-form-item>-->
    <!--          </el-form>-->
    <!--        </el-scrollbar>-->
    <!--      </el-tab-pane>-->
    <!--    </el-tabs>-->
  </div>
</template>

<script setup lang="ts" name="pagesWorkflowDrawerNode">
import type { FormRules } from 'element-plus'
import type { BusinessUIQueryColumnType } from '@/types/custom'
import { defineAsyncComponent, nextTick, reactive, ref } from 'vue'
import { useWfApi } from '@/api/wf'
import { useBaseApi } from '@/api/base'

const IconSelector = defineAsyncComponent(() => import('@/components/iconSelector/index.vue'))

interface Props {
  hideTool?: boolean
  uiFormItems: BusinessUIQueryColumnType[]
  jsplumbData: {
    nodeList: TypedAny[]
    lineList: TypedAny[]
  }
}

interface NodeSelectOption {
  title: string
  field: string | number
}

const props = defineProps<Props>()

// 定义子组件向父组件传值/事件
const emit = defineEmits(['submit', 'close'])

const { GetWorkFlowRole } = useWfApi()
const { GetTypeDictionary } = useBaseApi()

const validateId = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('请输入ID'))
  } else if (props.jsplumbData.nodeList.some((s) => s.id === value && s.id !== oldId.value)) {
    callback(new Error('节点中，该ID已存在！'))
  } else {
    callback()
  }
}

// 定义变量内容
const oldId = ref('')
const nodeFormRef = ref()
const extendFormRef = ref()
const state = reactive<WorkflowDrawerNodeState>({
  node: {
    icon: '',
    className: '',
    id: '',
    nodeId: '',
    form: [],
    nodeType: 0,
    approvalUserType: 0,
    descript: '',
    label: '',
    roleId: ''
  },
  form: {
    module: []
  },
  tabsActive: '1',
  loading: {
    extend: false
  }
})
// 必填验证
const nodeRules = reactive<FormRules<typeof state.node>>({
  id: [{ required: true, validator: validateId, trigger: 'blur' }],
  nodeId: [{ required: true, message: '请输入节点id', trigger: 'blur' }],
  type: [{ required: true, message: '请输入类型', trigger: 'blur' }],
  left: [{ required: true, message: '请输入left坐标', trigger: 'blur' }],
  top: [{ required: true, message: '请输入top坐标', trigger: 'blur' }],
  icon: [{ required: true, message: '请输入icon图标', trigger: 'blur' }],
  label: [{ required: true, message: '请输入名称', trigger: 'blur' }]
})
// 角色
const roleItems = ref<NodeSelectOption[]>([])
// 角色类型
const roleTypeItems = ref<NodeSelectOption[]>([])
// 角色关联
const roleRelTypeItems = [
  { title: '公司', field: 'org' },
  { title: '部门', field: 'dep' }
]
// 节点
const nodeTypes: NodeSelectOption[] = [
  { title: '审批', field: 2 },
  { title: '抄送', field: 3 }
]
// 流程类型
const approvalUserTypes: NodeSelectOption[] = [
  { title: '用户指定审批人', field: 0 },
  { title: '角色审批', field: 1 },
  { title: '程序指定', field: 2 }
]
// 获取父组件数据
const getParentData = (data: WorkflowDesignNode) => {
  if (data.form?.some((s) => s.prop === 'roleId')) {
    GetWorkFlowRole().then(({ data }) => {
      roleItems.value = data.map((v) => {
        return {
          field: v.id,
          title: v.name
        }
      })
    })
  }
  if (data.form?.some((s) => s.prop === 'roleType')) {
    GetTypeDictionary({ type_name: 'sys_base.Workflow.WfRoleItem' }).then(({ data }) => {
      roleTypeItems.value = data.map((v) => {
        return {
          field: v.value_text,
          title: v.display_text
        }
      })
    })
  }

  nextTick(() => {
    oldId.value = data.id
    state.node = data
  })
}
// 节点编辑-重置
const onNodeRefresh = () => {
  state.node.label = ''
  state.node.roleId = ''
  state.node.formEditItemList = []
  state.node.formSubmitUser = false
}
// 节点编辑-保存
const onNodeSubmit = () => {
  nodeFormRef.value.validate((valid: boolean) => {
    if (valid) {
      if (oldId.value && state.node.id !== oldId.value) {
        props.jsplumbData.lineList.forEach((v) => {
          if (v.sourceId === oldId.value) {
            v.sourceId = state.node.id
          } else if (v.targetId === oldId.value) {
            v.targetId = state.node.id
          }
        })
      }
      emit('submit', state.node)
      emit('close')
    } else {
      return false
    }
  })
}

// 扩展表单-重置
const onExtendRefresh = () => {
  extendFormRef.value.resetFields()
}
// // 扩展表单-保存
// const onExtendSubmit = () => {
//   extendFormRef.value.validate((valid: boolean) => {
//     if (valid) {
//       state.loading.extend = true
//       setTimeout(() => {
//         state.loading.extend = false
//         console.log(state.node)
//         ElMessage.success('保存成功')
//         emit('close', state.node)
//       }, 1000)
//     } else {
//       return false
//     }
//   })
// }

/**
 * 获取下拉数据
 * @param item
 */
const getOptions = (item: any) => {
  if (item.prop === 'nodeType') {
    return nodeTypes
  } else if (item.prop === 'approvalUserType') {
    return approvalUserTypes
  } else if (item.prop === 'roleId') {
    return roleItems.value
  } else if (item.prop === 'roleType') {
    return roleTypeItems.value
  } else if (item.prop === 'roleRelType') {
    return roleRelTypeItems
  } else if (item.prop === 'formEditItemList') {
    return props.uiFormItems
  } else {
    return []
  }
}

// 暴露变量
defineExpose({
  getParentData
})
</script>

<style scoped lang="scss">
.workflow-drawer-node {
  :deep(.el-tabs) {
    box-shadow: unset;
    border: unset;

    .el-tabs__nav {
      display: flex;
      width: 100%;

      .el-tabs__item {
        flex: 1;
        padding: unset;
        text-align: center;

        &:first-of-type.is-active {
          border-left-color: transparent;
        }

        &:last-of-type.is-active {
          border-right-color: transparent;
        }
      }
    }

    .el-tabs__content {
      padding: 0;
      height: calc(100vh - 90px);

      .el-tab-pane {
        height: 100%;
      }
    }
  }
}
</style>
